import { IDeviceCategory, IResponse } from '@/interfaces/common.interface';
import { Button, Cell, DropdownItem, DropdownMenu, Field, Icon, Switch } from 'vant';
import { Component, Vue } from 'vue-property-decorator';
import style from '../styles/device.module.less';

@Component({
  components: {
    'van-button': Button,
    'van-field': Field,
    'van-dropdown-menu': DropdownMenu,
    'van-dropdown-item': DropdownItem,
    'van-cell': Cell,
    'van-switch': Switch,
    'van-icon': Icon
  },
  sockets: {
    connect() {
      this.$socket &&
        this.$socket.client.emit('get-mqtt-status', (res: IResponse) => {
          if (res && res.result) {
            this.$data.mqttStatus = res.data;
          }
        });
    },

    message(data: { type: IDeviceCategory; data: string }) {
      console.log('message: ', data);
      if (data.type === 'mqtt') {
        this.$data.receiveMessage = data.data;
      }
    },

    mqttStatus(status: boolean) {
      this.$data.mqttStatus = status;
    }
  }
})
export default class Lora extends Vue {
  private sendMessage = '';
  private mqttStatus = false;
  private receiveMessage = '';

  private get hasNetworkPermission() {
    return this.$store.state.permissions && this.$store.state.permissions.network;
  }

  private get hasMqttPublishPermission() {
    return this.$store.state.permissions && this.$store.state.permissions.mqtt.publish;
  }

  private get hasMqttSubscribePermission() {
    return this.$store.state.permissions && this.$store.state.permissions.mqtt.subscribe;
  }

  public created() {
    this.$socket &&
      this.$socket.client.emit('get-mqtt-status', (res: IResponse) => {
        if (res && res.result) {
          this.mqttStatus = res.data;
        }
      });
  }

  public render() {
    return (
      <div class={style['device-message']}>
        <p class={style['device-message-title']}>【连接MQTT服务（默认配置）】：</p>
        <van-switch
          value={this.mqttStatus}
          active-color='#07c160'
          onchange={this.switchChange}
        />
        <div class={style['device-message-content']}>
          <p class={style['device-message-title']}>【发送 message 主题消息】：</p>
          <div class={style['device-message-send']}>
            <van-field v-model={this.sendMessage} rows='3' autosize type='textarea' placeholder='请输入要发送的消息' />
          </div>

          <div class={style['device-message-btn']}>
            <van-button size='small' on-click={this.submitMessage} disabled={!this.mqttStatus} plain hairline color='#20a5de'>
              send
            </van-button>
          </div>

          <p class={style['device-message-title']}>【监听 message 主题消息】：</p>
          <div class={style['device-message-response']}>
            <van-field
              value={this.receiveMessage}
              readonly
              rows='3'
              autosize
              type='textarea'
            />
          </div>
        </div>

        {/* 权限判断 */}
        {(!this.hasNetworkPermission || !this.hasMqttPublishPermission || !this.hasMqttSubscribePermission) && (
          <div class={style['permission']}>
            <p>
              当前模块需要开启<span>{` 网络通信、MQTT发布、订阅权限 `}</span>，请按照以下路径进行手动配置：
            </p>
            <span>{`设置 > 隐私设置 > 应用权限 > 设备通信 > 系统权限 > ...`}</span>
          </div>
        )}
      </div>
    );
  }

  private switchChange(v: boolean) {
    this.$socket.client.emit('change-mqtt-status', v, (res: IResponse) => {
      if (!res || !res.result) {
        this.$edger.notify.error(res.message || `${v ? '开启' : '关闭'}MQTT服务失败！`);
      }
    });
  }

  /* 发送设备消息 */
  private submitMessage() {
    this.$socket.client.emit('send-message', { type: 'mqtt', data: this.sendMessage }, (res: any) => {
      if (!res || !res.result) {
        this.$edger.notify.error(res.message || '操作失败！');
      }
    });
  }
}
